package com.rampage.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 操作Redis数据库工具类
 * Serializer使用JdkSerializationRedisSerializer
 * 使用时需要在spring配置文件中声明connectionFactory
 * @author WuJW
 *      
 */
@Component
public class RedisUtils<K, T> implements InitializingBean {

	@Autowired
	private RedisConnectionFactory connectionFactory;
	
	private RedisTemplate redisTemplate;

	public void afterPropertiesSet(){
		redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);
		redisTemplate.setEnableDefaultSerializer(true);
		redisTemplate.setDefaultSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.afterPropertiesSet();
	}
	
	public T get(K key) {
		return (T) redisTemplate.boundValueOps(key).get();
	}

	public void save(K key, T value) {
		redisTemplate.boundValueOps(key).set(value);
	}
	
	public void save(K key, T value, long offset) {
		redisTemplate.boundValueOps(key).set(value, offset);
	}
	
	public void save(K key, T value, long timeout, TimeUnit unit) {
		redisTemplate.boundValueOps(key).set(value, timeout, unit);
	}
	
	public void delete(K key) {
		redisTemplate.delete(key);
	}

	public RedisConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}

	public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

}
